package com.biconn.bigdata.jstrom.util;


import com.biconn.bigdata.common.util.StringTools;
import com.google.common.collect.Maps;
import org.apache.commons.io.IOUtils;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.io.StringReader;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Auther: 123774135@qq.com
 * @Date: 2018/8/2 17:40
 * @projectname: botu
 * @Description:
 */
public class RegularExpress {


    private static   final String XML_PATH = "//rules/rule";

    private static   final String XML_NAME = "regularerule.xml";

    public static Map<String,String>  loadXml(){
        Map<String,String> ruleMap = Maps.newHashMap();
        InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(XML_NAME);
        try {
            String str_xml = IOUtils.toString(inputStream);
            //进行解析xml
            List<Element> list = builderElements(str_xml);
            if(null == list){
                throw new NullPointerException("集合为空!");
            }
            for(Element e : list){
                Node node_code = e.selectSingleNode(Dictionary.CODE.name().toLowerCase());
                Node node_express = e.selectSingleNode(Dictionary.EXPRESS.name().toLowerCase());
                //System.out.println(StringTools.mkString(node_code.getText()));
                //System.out.println(node_express.getText());
                ruleMap.put(StringTools.mkString(node_code.getText()),StringTools.mkString(node_express.getText()));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            IOUtils.closeQuietly(inputStream);
        }
        return ruleMap;
    }


    private static List<Element> builderElements(String str_xml){
        SAXReader reader = new SAXReader(); //1.创建一个xml解析器对象
        Document document = null;
        try {
            document = reader.read(new StringReader(str_xml));
            List<Element> list = document.selectNodes(XML_PATH);
            return list;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }



    public static String getValue(String str,Pattern pattern){
        String sex = "";
        Matcher m = pattern.matcher(str);
        while(m.find()){
            sex = sex + m.group() ;
        }
        return sex;
    }

    public static String getValue(String str,Pattern pattern,String formate){
        StringBuffer sb = new StringBuffer(32);
        Matcher m = pattern.matcher(str);
        while(m.find()){
            sb.append(m.group()).append(formate);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        RegularExpress.loadXml();
    }

}
